package com.monolithiot.sso.controller.front;

import com.monolithiot.sso.common.context.Constants;
import com.monolithiot.sso.common.entity.Authorization;
import com.monolithiot.sso.common.util.CookieUtil;
import com.monolithiot.sso.common.util.ReturnUrlUtil;
import com.monolithiot.sso.common.util.SessionAttributeUtil;
import com.monolithiot.sso.controller.ControllerSupport;
import com.monolithiot.sso.service.AuthorizationService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

/**
 * 2018/12/13 Create by 郭文梁
 * AuthorizationPageController
 * 授权相关u二面控制器
 *
 * @author 郭文梁
 * @date 2018/12/13
 */
@Controller
@RequestMapping("/front/authorization-page")
public class AuthorizationPageController implements ControllerSupport {
    private final AuthorizationService authorizationService;

    @Autowired
    public AuthorizationPageController(AuthorizationService authorizationService) {
        this.authorizationService = authorizationService;
    }

    /**
     * 执行授权逻辑
     *
     * @param returnUrl 返回路径
     * @param session   会话
     * @param request   请求对象
     * @return 的视图名（重定向道）
     */
    @GetMapping("/auth")
    public String auth(@RequestParam String returnUrl, HttpSession session, HttpServletRequest request) {
        //检查当前会话是否已授权
        Authorization authorization = SessionAttributeUtil.fromSession(session, Authorization.class, Constants.Key.SESSION_AUTHORIZATION);

        //检查Cookie是否有Token
        if (authorization == null) {
            authorization = findCookieToken(request);
        }

        if (authorization == null) {
            //未授权，保存返回地址，进入登录页面
            SessionAttributeUtil.put(session, Constants.Key.SESSION_AUTHORIZATION_RETURN_URL, returnUrl);
            return Constants.View.redirect(Constants.View.LOGIN_VIEW);
        }

        String targetUrl = ReturnUrlUtil.appendToken(returnUrl, authorization.getToken());
        return Constants.View.redirect(targetUrl);
    }

    /**
     * 获取Cookie中的token并查询出Authorization
     *
     * @param request Http请求对象
     * @return Authorization对象
     */
    private Authorization findCookieToken(HttpServletRequest request) {
        Cookie cookie = CookieUtil.rememberCookirFromRequest(request);
        if (cookie == null) {
            return null;
        }
        return authorizationService.findByToken(cookie.getValue());
    }
}
